package com.simpou.commons.persistence.jpa.helper;

import com.simpou.commons.persistence.Parameters;
import com.simpou.commons.persistence.dao.TypedDAO;
import com.simpou.commons.persistence.jpa.dao.impl.AbstractTypedJpaDAOImpl;
import com.simpou.commons.utils.tests.TestRunner;
import com.simpou.commons.utils.tests.annot.ClassTest;
import static org.junit.Assert.*;

import org.junit.Test;

import org.junit.runner.RunWith;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import javax.validation.ConstraintViolationException;


@ClassTest(JpaExceptionHelper.class)
@RunWith(TestRunner.class)
public class JpaExceptionHelperITCase {
    @Test
    public void testToString() throws Exception {
        TypedDAO<TestEmHelperEntity> dao = new AbstractTypedJpaDAOImpl<TestEmHelperEntity>(TestEmHelperEntity.class) {
                final EntityManager em = Persistence.createEntityManagerFactory(Parameters.PU_NAME)
                                                    .createEntityManager();

                @Override
                protected EntityManager getEntityManager() {
                    return em;
                }
            };

        TestEmHelperEntity entity = new TestEmHelperEntity();
        entity.fillRandomInvalid();
        dao.getTransaction().begin();

        try {
            dao.create(entity);
        } catch (ConstraintViolationException ex) {
            String message = JpaExceptionHelper.toString(ex);
            assertNotNull(message);
        }

        dao.getTransaction().rollback();
    }
}
